package com.weilive.platform.gate.json.handler;

import org.springframework.stereotype.Service;

import com.weilive.core.netty.NettyErrors;
import com.weilive.core.protocol.json.JsonRequest;
import com.weilive.core.protocol.json.JsonRequestHandler;
import com.weilive.core.protocol.json.JsonResponse;
import com.weilive.core.utils.RegexUtils;
import com.weilive.platform.PlatformConstants;
import com.weilive.platform.PlatformErrors;
import com.weilive.platform.PlatformMail;
import com.weilive.platform.PlatformMail.Mail;
import com.weilive.platform.cache.user.UserManager;
import com.weilive.platform.cache.user.UserObj;
import com.weilive.platform.dao.user.mapper.UserTokenDO;
import com.weilive.platform.gate.json.protocol.CSA_PlatUserForgetPwd;
import com.weilive.platform.gate.json.protocol.CSQ_PlatUserForgetPwd;
/**
 * 用户忘记密码
 * @author houge
 *
 */
@Service
public class CSQ_PlatUserForgetPwd_JsonHandler extends JsonRequestHandler {
	
	private static final String mail_subject = "<<泰时明月>>找回密码";
	private static final String content_format = "<a href=\"%s/user/password/reset?token=%s\"> 点击此处 </a>重置密码";
	
    public Class<?> getRequestType() {
        return CSQ_PlatUserForgetPwd.class;
    }

    public Class<?> getResponseType() {
        return CSA_PlatUserForgetPwd.class;
    }

    public JsonResponse handleRequest(JsonRequest request) throws Exception {
        CSQ_PlatUserForgetPwd params = (CSQ_PlatUserForgetPwd) request.getData();
        CSA_PlatUserForgetPwd response = new CSA_PlatUserForgetPwd();
        if (params.email == null && params.phone == null) {
        	return createErrorResponse(NettyErrors.BAD_REQUEST);
        }
        if (params.email != null && RegexUtils.isEmail(params.email) == false) {
			return createErrorResponse(PlatformErrors.INVALID_EMAIL);
		}
		if (params.phone != null && RegexUtils.isPhone(params.phone) == false) {
			return createErrorResponse(PlatformErrors.INVALID_PHONE);
		}
        UserObj user = params.email != null ? UserManager.getUserByEmail(params.email) : UserManager.getUserByPhone(params.phone);
        if (user == null) {
        	return createErrorResponse(PlatformErrors.USER_NOT_EXIST);
        }
        if (params.email != null) {
        	UserTokenDO token = UserManager.updateUserToken(user.info.user_id, PlatformConstants.TOKEN_TYPE_FORGET_PWD, PlatformConstants.TOKEN_TYPE_FORGET_PWD_EXPIRED);
        	PlatformMail.sendMail(new Mail(params.email, mail_subject, String.format(content_format, PlatformMail.getForgetPasswordHost(), token.token)));
        } else {
        	// TODO 短信找回密码
        }
        return JsonResponse.create(response);
    }

}
